<template>
  <div class="page-container">
    <el-card class="bill-card">
      <!-- 账单信息 -->
      <div class="bill-info">
        <template v-for="(label, key) in billLabels" :key="key">
          <div class="info-item" v-if="displayBillInfo[key] !== undefined">
            <span class="label">{{ label }}：</span>
            <span :class="{ status: key === 'billStatus' }">
              {{ displayBillInfo[key] ?? '-' }}
            </span>
          </div>
        </template>
      </div>

      <!-- 账单明细表 -->
      <el-table
        :data="billDetails"
        border
        style="margin-top: 20px"
        :header-cell-style="{ background: '#f5f7fa', fontWeight: 'bold' }"
      >
        <el-table-column prop="type" label="类型" align="center" width="120" />
        <el-table-column prop="feeItem" label="费用项目" align="center" width="180" />
        <el-table-column prop="serviceContent" label="服务内容" align="center" />
        <el-table-column prop="amount" label="金额（元）" align="right">
          <template #default="scope">
            <span
              :class="[
                scope.row.amount < 0 ? 'minus' : '',
                scope.row.type === '小计' ||
                scope.row.type === '账单金额' ||
                scope.row.type === '应付金额'
                  ? 'highlight'
                  : ''
              ]"
            >
              {{ scope.row.amount.toFixed(2) }}
            </span>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 返回按钮 -->
    <div class="back-btn-container">
      <el-button type="primary" @click="goBack">返回</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getBillListByBillNo } from '@/api/finance/billList'

// 路由
const route = useRoute()
const router = useRouter()

// 账单信息
const billInfo = ref({})
const billDetails = ref([])

// 字段映射
const billLabels = {
  billNo: '账单编号',
  billMonth: '账单月份',
  elderName: '老人姓名',
  elderIdCard: '老人身份证号',
  billAmount: '账单金额（元）',
  payableAmount: '应付金额（元）',
  prepaidAmount: '预收款（元）',
  depositAmount: '押金（元）',
  currentPayable: '本期应付（元）',
  billPeriod: '账单周期',
  totalDays: '共计天数（天）',
  billStatus: '交易状态',
  paymentDeadline: '支付截止时间',
  createdBy: '创建人',
  createdAt: '创建时间'
}

// 计算属性：用于美化显示账单信息
const displayBillInfo = computed(() => {
  const info = billInfo.value
  const result = { ...info }

  if (info.billNo) {
    result.billNo = info.billType === '0' ? `月度账单-${info.billNo}` : `普通账单-${info.billNo}`
  }

  const statusMap = {
    '0': '待支付',
    '1': '已支付',
    '2': '已作废',
    '3': '审批中'
  }
  result.billStatus = statusMap[info.billStatus] ?? '-'

  // 账单周期
  if (info.billStartTime && info.billEndTime) {
    const start = new Date(info.billStartTime)
    const end = new Date(info.billEndTime)
    result.billPeriod = `${info.billStartTime.slice(0, 10)} 至 ${info.billEndTime.slice(0, 10)}`
    result.totalDays = Math.ceil((end - start) / (1000 * 60 * 60 * 24))
  } else {
    result.billPeriod = '-'
  }

  // 金额格式化
  const moneyFields = ['billAmount', 'payableAmount', 'prepaidAmount', 'depositAmount', 'currentPayable']
  moneyFields.forEach((field) => {
    if (info[field] != null) result[field] = parseFloat(info[field]).toFixed(2)
  })

  if (info.paymentDeadline) {
    result.paymentDeadline = info.paymentDeadline.slice(0, 10)
  }
  if (info.createdAt) {
    result.createdAt = info.createdAt.slice(0, 10)
  }

  return result
})

// 页面加载逻辑
onMounted(() => {
  const billNo = route.query.billNo
  if (!billNo) return

  getBillListByBillNo(billNo).then((res) => {
    billInfo.value = res.data || {}
    const info = res.data || {}

    // 动态构建账单明细
    billDetails.value = [
      {
        type: '添加项',
        feeItem: '护理费用',
        serviceContent: info.careLevelName || '-',
        amount: info.careFee ?? 0
      },
      {
        type: '添加项',
        feeItem: '床位费用',
        serviceContent: info.roomTypeName || '-',
        amount: info.bedFee ?? 0
      },
      {
        type: '添加项',
        feeItem: '其他费用',
        serviceContent: '-',
        amount: 0.0
      },
      {
        type: '扣减项',
        feeItem: '医保支付',
        serviceContent: '—',
        amount: 0.0
      },
      {
        type: '扣减项',
        feeItem: '政府补贴',
        serviceContent: '—',
        amount: 0.0
      },
      {
        type: '小计',
        feeItem: '-',
        serviceContent: '-',
        amount: (info.careFee ?? 0) + (info.bedFee ?? 0)
      },
      {
        type: '账单金额',
        feeItem: '-',
        serviceContent: '-',
        amount: info.billAmount ?? 0
      },
      {
        type: '押金',
        feeItem: '-',
        serviceContent: '-',
        amount: info.depositAmount ?? 0
      },
      {
        type: '预收款支付',
        feeItem: '-',
        serviceContent: '-',
        amount: info.prepaidAmount ?? 0
      },
      {
        type: '应付金额',
        feeItem: '-',
        serviceContent: '-',
        amount: info.payableAmount ?? 0
      }
    ]
  })
})

// 返回按钮逻辑
const goBack = () => {
  router.push('/finance/bill/billList')
}
</script>

<style scoped>
.page-container {
  width: 100%;
  min-height: 100vh;
  padding: 20px;
  background: #fff;
  box-sizing: border-box;
}

.bill-card {
  width: 100%;
  max-width: 1400px;
  margin: 0 auto;
}

.bill-info {
  display: flex;
  flex-wrap: wrap;
  gap: 20px 40px;
  padding: 20px 0;
}

.info-item {
  width: calc(50% - 20px);
  display: flex;
  align-items: center;
}

.label {
  font-weight: bold;
  margin-right: 8px;
  min-width: 120px;
  text-align: right;
}

.status {
  color: #409eff;
}

.el-table {
  --el-table-row-hover-bg-color: #fafafa;
}

.minus {
  color: #ff4d4f;
}

.highlight {
  font-weight: bold;
  color: #333;
}

.back-btn-container {
  text-align: center;
  margin-top: 40px;
}
</style>
